跳至主要内容

dropRightWhile

🔸 題目描述

請實作一個名為 dropRightWhile 的函式,該函式接收兩個參數。第一個參數是一個陣列;第二個參數是一個 predicate 函式,用於指定條件。

dropRightWhile 函式會從陣列的末端開始遍歷,移除符合指定條件的元素,直到遇到不符合條件的元素為止。然後,它會回傳剩餘的元素所組成的新陣列,同時確保原始陣列保持不變。

// 範例一
dropRightWhile(
["hello", "world", "today", "isGood"],
(value) => value.length > 5,
);
// => ['hello', 'world', 'today']
// 範例二
dropRightWhile(
[
{ name: "Alice", age: 25 },
{ name: "Charlie", age: 20 },
{ name: "Bob", age: 30 },
],
(obj) => obj.age > 25,
);
// => [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 20 }]

// 範例三
dropRightWhile([10, 20, 30, 40, 50, 10], (value) => value !== 10);
// => [10, 20, 30, 40, 50, 10]

// 範例四
dropRightWhile([1], (value) => value > 0);
// => []

Tests

import { describe, expect, it } from "@jest/globals";
import dropRightWhile from "./dropRightWhile";

describe("dropRightWhile", () => {
it("should drop elements from the end of the array until the predicate returns false", () => {
const result = dropRightWhile(
["hello", "world", "today", "isGood"],
(value) => value.length > 5,
);
expect(result).toEqual(["hello", "world", "today"]);
});

it("should drop objects from the end of the array until the predicate returns false", () => {
const result = dropRightWhile(
[
{ name: "Alice", age: 25 },
{ name: "Charlie", age: 20 },
{ name: "Bob", age: 30 },
],
(obj) => obj.age > 25,
);
expect(result).toEqual([
{ name: "Alice", age: 25 },
{ name: "Charlie", age: 20 },
]);
});

it("should return the original array if no elements need to be dropped", () => {
const result = dropRightWhile(
[10, 20, 30, 40, 50, 10],
(value) => value !== 10,
);
expect(result).toEqual([10, 20, 30, 40, 50, 10]);
});

it("should return an empty array if all elements need to be dropped", () => {
const result = dropRightWhile([1], (value) => value > 0);
expect(result).toEqual([]);
});
});

Solutions

function dropRightWhile(array, predicate) {
let index = array.length - 1;
while (index >= 0 && predicate(array[index])) {
index--;
}
return array.slice(0, index + 1);
}